#include <stdio.h>  
#include <stdlib.h>  
#include <assert.h>  
#include <string.h>  
#include <unistd.h>  
#include <pwd.h>  
#define PATH "/home/"   
  
void print_info()  
{  
    uid_t id = getuid();  
    char *status = "$";  
    if( id == 0)  
    {  
        status = "#";  
    }  
    struct passwd *p = getpwuid(id);  
    if(p == NULL)  
    {  
        printf("mybash>>");  
        fflush(stdout);  
        return;  
    }  
      
    char path[128] = {0};  
    getcwd(path,256);  
      
    char *q = "/";  
    char *s = strtok(path,"/");  
    while( s != NULL)  
    {  
        q = s;  
        s = strtok(NULL,"/");  
    }  
    char hostname[128] = {0};  
    gethostname(hostname,128);  
    printf("[%s@%s %s]%s ",p->pw_name,hostname,q,status);  
}  
int main()  
{  
    while(1)  
    {  
        print_info();  
        char buff[128] = {0};  
        fgets(buff,128,stdin);  
        buff[strlen(buff)-1] = 0;  
        char *myargv[10] = {0};  
        char *s = strtok(buff," ");  
        if(s == NULL)  
        {  
            continue;  
        }  
        myargv[0] = s;  
        int i = 1;  
        while((s = strtok(NULL," ")) != NULL)  
        {  
            myargv[i++] = s;  
        }  
        if(strcmp(myargv[0],"exit") == 0)  
        {  
            exit(0);  
        }     
        else if(strcmp(myargv[0],"cd") == 0)  
        {  
            if(chdir(myargv[1]) == -1)  
            {  
                perror("chdir error");  
            }  
            continue;  
        }  
        pid_t pid = fork();  
        assert(pid != -1);  
        if(pid == 0)  
        {   
            char path[256] = {0};  
            if(strncmp(myargv[0],"./",2) != 0 && strncmp(myargv[0],"/",1) != 0)  
            {  
                strcpy(path,PATH);  
            }  
            strcat(path,myargv[0]);  
            execv(path,myargv);  
            perror("execv error");  
            exit(0);  
        }  
        else  
        {  
            wait(NULL);  
        }      
    }  
}  

